from django.core.exceptions import ValidationError
from django.shortcuts import render, redirect

from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.encrypt import md5


def admin_list(request):
    """管理员列表"""

    data_dict = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dict = {'username__contains': search_data}

    # 根据搜索条件去数据库获取
    queryset = models.Admin.objects.filter(**data_dict)

    # 分页
    page_object = Pagination(request, queryset)
    context = {
        'queryset': queryset,
        'page_string': page_object.html(),
        'search_data': search_data,
    }
    return render(request, 'admin_list.html', context)


from django import forms
from app01.utils.bootstrap import BootStrapModelForm


class AdminModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput
    )

    class Meta:
        model = models.Admin
        fields = ['username', 'password', 'confirm_password']
        widgets = {
            'password': forms.PasswordInput
        }

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)

    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm_password = md5(self.cleaned_data.get('confirm_password'))
        if password == confirm_password:
            return confirm_password
        else:
            raise ValidationError('两次密码不一致')


class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput
    )

    class Meta:
        model = models.Admin
        fields = ['password', 'confirm_password']
        widgets = {
            'password': forms.PasswordInput
        }

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        md5_pwd = md5(pwd)

        # 去数据库校验当前密码和输入的密码是否一致
        if models.Admin.objects.filter(password=md5_pwd).exists():
            raise forms.ValidationError('密码已存在')

        return md5(pwd)

    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm_password = md5(self.cleaned_data.get('confirm_password'))
        if password == confirm_password:
            return confirm_password
        else:
            raise forms.ValidationError('两次密码不一致')


def admin_add(request):
    """管理员添加"""
    # 添加用户
    if request.method == 'GET':
        form_obj = AdminModelForm()
        return render(request, 'admin_add.html', {'form_obj': form_obj})

    form_obj = AdminModelForm(request.POST)
    if form_obj.is_valid():
        form_obj.save()
        return redirect('/admin/list')
    context = {
        'form_obj': form_obj,
    }
    return render(request, 'admin_add.html', context)


def admin_edit(request, nid):
    """管理员编辑"""
    # 编辑用户
    obj = models.Admin.objects.filter(id=nid).first()
    if request.method == 'GET':
        form_obj = AdminModelForm(instance=obj)
        return render(request, 'admin_edit.html', {'form_obj': form_obj})

    form_obj = AdminModelForm(request.POST, instance=obj)
    if form_obj.is_valid():
        form_obj.save()
        return redirect('/admin/list')
    context = {
        'form_obj': form_obj,
    }
    return render(request, 'admin_edit.html', context)


def admin_delete(request, nid):
    """管理员删除"""
    models.Admin.objects.filter(id=nid).delete()
    return redirect('/admin/list')


def admin_reset(request, nid):
    """管理员重置密码"""
    obj = models.Admin.objects.filter(id=nid).first()
    if not obj:
        return redirect('/admin/list')

    title = '管理员重置密码-{}'.format(obj.username)
    if request.method == 'GET':
        form = AdminResetModelForm()
        return render(request, 'admin_reset.html', {'form': form, 'title': title})

    form = AdminResetModelForm(request.POST, instance=obj)
    if form.is_valid():
        form.save()
        return redirect('/admin/list')
    return render(request, 'admin_reset.html', {'form': form, 'title': title})